package com.gzhu.knowledgeAdmin.controller;


import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzhu.knowledgeAdmin.common.result.R;
import com.gzhu.knowledgeAdmin.controller.dto.BlackListDto;
import com.gzhu.knowledgeAdmin.controller.dto.ExportBlackListDto;
import com.gzhu.knowledgeAdmin.entity.THmdT;
import com.gzhu.knowledgeAdmin.service.THmdTService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/hmd")
public class BlackListController {

    @Resource
    private THmdTService tHmdTService;

    @PostMapping("/find")
    public R findByGsid(@RequestBody THmdT tHmdT)
    {
        List<THmdT> hmd = tHmdTService.getHmd(tHmdT);
        return R.ok(hmd);
    }


    @PostMapping("/add")
    public R addBlacklist(@RequestBody BlackListDto blacklistDTO) {
        String[] phoneNumbers = blacklistDTO.getFKhsjhm().split("\\n");
        for(String phoneNumber: phoneNumbers){
            THmdT tHmdT = new THmdT(blacklistDTO.getFGqsj(), phoneNumber.trim(), blacklistDTO.getFBz());
            tHmdTService.addBlacklist(tHmdT);
        }
        return R.ok();
    }

    @PostMapping("/del/{fId}")
    public R deleteById(@PathVariable Long fId)
    {
        return R.ok(tHmdTService.removeById(fId));
    }

    @PostMapping("/del/batchDelete")
    public R deleteBatch(@RequestBody List<Integer> ids) {
        return R.ok(tHmdTService.removeByIds(ids));
    }


    @PostMapping("/update")
    public R updateTask(@RequestBody THmdT tHmdT)
    {
        return R.ok(tHmdTService.updateBlacklist(tHmdT));
    }


    /**
     * 导出接口
     */
    @GetMapping("/export")
    public R export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        QueryWrapper<THmdT> queryWrapper = new QueryWrapper<>();
        List<THmdT> list = tHmdTService.list(queryWrapper);

        for (THmdT item : list)
        {
            if ("0".equals(item.getFLx()))
            {
                item.setFLx("手工导入");
            }
            else if ("1".equals(item.getFLx()))
            {
                item.setFLx("批量导入");
            }
        }
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("fId", "id");
        writer.addHeaderAlias("fKhsjhm", "手机号");
        writer.addHeaderAlias("fLx", "导入方式");
        writer.addHeaderAlias("fSxsj", "生效时间");
        writer.addHeaderAlias("fGqsj", "有效期");
        writer.addHeaderAlias("fBz", "备注");
        List<ExportBlackListDto> exportedList = list.stream()
                .map(item -> new ExportBlackListDto(
                        item.getFId(),
                        item.getFKhsjhm(),
                        item.getFLx(),
                        item.getFSxsj(),
                        item.getFGqsj(),
                        item.getFBz()
                ))
                .collect(Collectors.toList());

        writer.setColumnWidth(1, 15);
        writer.setColumnWidth(3, 20);
        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(exportedList, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("黑名单信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
        return R.ok();
    }

}